﻿using System.Windows;
using System.Windows.Input;
using System.Windows.Interactivity;
using DevExpress.Xpf.Grid;

namespace Loki.UI.Wpf.Behaviours
{
    public class TableViewRowDoubleClickBehavior : Behavior<GridControl>
    {
        public ICommand Command { get; set; }

        protected override void OnAttached()
        {
            base.OnAttached();
            AssociatedObject.Loaded += AssociatedObject_Loaded;
        }

        private void AssociatedObject_Loaded(object sender, RoutedEventArgs e)
        {
            TableView gridView = AssociatedObject.View as TableView;
            if (gridView != null)
            {
                gridView.RowDoubleClick += gridView_RowDoubleClick;
            }
        }

        protected override void OnDetaching()
        {
            AssociatedObject.Loaded -= AssociatedObject_Loaded;
            TableView gridView = AssociatedObject.View as TableView;
            if (gridView != null)
            {
                gridView.RowDoubleClick -= gridView_RowDoubleClick;
            }

            base.OnDetaching();
        }

        private void gridView_RowDoubleClick(object sender, RowDoubleClickEventArgs e)
        {
            if (Command != null)
            {
                if (e.HitInfo.InColumnHeader == false
                && e.HitInfo.InColumnPanel == false
                && e.HitInfo.InFilterPanel == false
                && e.HitInfo.InGroupColumn == false
                && e.HitInfo.InGroupPanel == false
                && e.HitInfo.InRow == true)
                {
                    var item = AssociatedObject.GetRow(e.HitInfo.RowHandle);
                    Command.Execute(item);
                }
            }
        }
    }
}